package team.kirohuji.utils;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


/**
 * 序列化类
 * @author kirohuji
 *
 */
public class SerializableUtils {

    /**
     * 这个方法用于序列化
     * @param session 会话对象
     * @return String
     */
    public static String serialize(Session session) {
    	
        try {
        	
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            
            oos.writeObject(session);
            
            return Base64.encodeToString(bos.toByteArray());
            
        } catch (Exception e) {
            throw new RuntimeException("serialize session error", e);
        }
    }
    
    /**
     * 这个方法用于反序列化
     * @param sessionStr 会话值
     * @return Session
     */
    public static Session deserialize(String sessionStr) {
    	
        try {
        	
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(sessionStr));
            
            ObjectInputStream ois = new ObjectInputStream(bis);
            
            return (Session)ois.readObject();
            
        } catch (Exception e) {
            throw new RuntimeException("deserialize session error", e);
        }
    }
}
